from flask import Flask, jsonify, request
import os

app = Flask(__name__)

# 递归获取目录结构的函数
def get_directory_structure(path):
    """
    获取指定路径的目录结构，并递归下去
    返回格式: { folder_name: { file_name: None or folder_name: {...}}}
    """
    structure = {}
    
    # 如果是目录，继续递归
    if os.path.isdir(path):
        for item in os.listdir(path):
            item_path = os.path.join(path, item)
            if os.path.isdir(item_path):  # 目录
                structure[item] = get_directory_structure(item_path)
            else:  # 文件
                structure[item] = None
    return structure

@app.route('/get_structure', methods=['GET'])
def get_structure():
    """
    API接口，接收路径参数，返回该路径下的目录结构JSON
    """
    folder_path = request.args.get('path')
    
    if not folder_path:
        return jsonify({
            "code": 1,
            "msg": "路径不能为空",
            "data": {}
        })
    
    if not os.path.exists(folder_path):
        return jsonify({
            "code": 2,
            "msg": "路径不存在",
            "data": {}
        })

    try:
        # 获取目录结构
        structure = get_directory_structure(folder_path)
        return jsonify({
            "code": 0,
            "msg": "成功",
            "data": structure
        })
    except Exception as e:
        return jsonify({
            "code": 3,
            "msg": f"错误：{str(e)}",
            "data": {}
        })

if __name__ == '__main__':
    app.run(debug=True)
